package top.duogong.grpcdemo;

import io.grpc.Grpc;
import io.grpc.InsecureChannelCredentials;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import top.duogong.grpcdemo.proto.*;

import java.util.concurrent.TimeUnit;

@Slf4j
@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) throws InterruptedException {

        SpringApplication.run(MainApplication.class, args);

        // 创建通道
        ManagedChannel channel = Grpc.newChannelBuilder("localhost:8080", InsecureChannelCredentials.create()).build();

        // 阻塞进程
        UserServiceGrpc.UserServiceBlockingStub stub = UserServiceGrpc.newBlockingStub(channel);

        // 创建请求 加入参数
        GetUserRequest getUserRequest = GetUserRequest.newBuilder().setId(1).build();

        // 测试第二个请求
        CreateUserRequest createUserRequest = CreateUserRequest.newBuilder().setUsername("admin").setEmail("admin@qq.com").build();

        log.info("正在访问服务端...");

        // 发送请求
        GetUserResponse getUserResponse = stub.getUser(getUserRequest);
        // 发送第二个请求
        CreateUserResponse createUserRespone = stub.createUser(createUserRequest);

        // 响应
        top.duogong.grpcdemo.proto.User user = getUserResponse.getUser();

        top.duogong.grpcdemo.proto.User user2 = createUserRespone.getUser();

        log.info("获取数据成功:{}", user);

        log.info("获取数据成功:{}", user2);

        // 关闭通道
        channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS);

    }
}
